import { login, logout, getInfo } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { isHttp } from '@/utils/validate';
import { TOKEN_RESPONSE_FIELD } from '@/constants/token-constants';
import defaultAvatar from '@/assets/images/profile.png';

/**
 * 格式解析头像地址
 * @param avatar 头像路径
 * @returns url地址
 */
function parseAvatar(avatar) {
  if (!avatar) {
    return defaultAvatar;
  }
  if (isHttp(avatar)) {
    return avatar;
  }
  const baseApi = import.meta.env.VITE_APP_BASE_API;
  return `${baseApi}${avatar}`;
}

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then(res => {
            if (res.code === 200 && res.data) {
              const token = res.data[TOKEN_RESPONSE_FIELD];
              setToken(token);
              this.token = token;
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(res => {
            if (res.code === 200 && res.data) {
              const { user, roles, permissions } = res.data;
              this.name = user.userName;
              this.avatar = parseAvatar(user.avatar);

              // 验证返回的roles是否是一个非空数组
              if (Array.isArray(roles) && roles.length > 0) {
                this.roles = roles;
                this.permissions = permissions;
              } else {
                this.roles = ['ROLE_DEFAULT'];
                this.permissions = [];
              }
              resolve(res);
              return;
            }
            // 网络错误时退出登录状态
            if (res.code === 500) {
              removeToken();
              window.location.reload();
              reject(res);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 退出系统
    logOut() {
      return new Promise(resolve => {
        logout(this.token).finally(() => {
          this.token = '';
          this.roles = [];
          this.permissions = [];
          removeToken();
          resolve();
        });
      });
    },
  },
});

export default useUserStore;
